'use strict';

import AddressComponent from '../../prototype/addressComponent';
import Cities from '../../models/v1/cities';
import CityHandle from './cities'

class SearchPlace extends AddressComponent {
  constructor() {
    super()
    this.search = this.search.bind(this)
  }
  /**
   * 关键词搜索地址
   * @url  /api/v1/pois?city_id=51&keyword=黄旗山
   * @param {number} city_id 城市id
   * @param {String} keyword  关键词
   */
  async search (ctx,next) {
    let { type = 'search', city_id, keyword } = ctx.query;
    if (!keyword) {
      ctx.body = {
        name: 'ERROR_QUERY_TYPE',
        message: '参数错误',
      }
    } else if (isNaN(city_id)) {
      try {
        // 获取定位城市拼音
        const cityname = await CityHandle.getCityName(ctx.request)
        // 获取城市信息
        const cityInfo = await Cities.cityGuess(cityname);
        // 获取查询回来的城市ID
        city_id = cityInfo.id;
      } catch (err) {
        console.log('搜索地址时，获取定位城失败')
        ctx.body = {
          name: 'ERROR_GET_POSITION',
          message: '获取数据失败',
        }
      }
    }

    try {
      const cityInfo = await Cities.getCityById(city_id);
      console.log(cityInfo);
      const resObj = await this.searchPlace(keyword, cityInfo.name, type);
      const cityList = [];
      resObj.data.forEach((item,inndex) => {
        cityList.push({
          name: item.title,
          address: item.address,
          latitude: item.location.lat,
          longitude: item.location.lng,
          geohash: item.location.lat + ',' + item.location.lng
        })
      })
      ctx.body = cityList
    } catch (err) {
      ctx.body = {
        name: 'GET_ADDRESS_ERROR',
        message: '获取地址信息失败',
      }
    }
  }
}

export default new SearchPlace()